package com.huicharge.huichargecrm.rpc;

import com.ludaniu.common.Invocation;
import com.ludaniu.common.NettyHeader;
import com.ludaniu.common.Packmsg;
import com.ludaniu.netty.utils.SerDerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author 鲁昊天
 * @version 1.0
 * @BelongsProject:huicharge-crm-learn
 * @BelongsPackage:com.huicharge.huichargecrm.rpc
 * @Description <p>
 * <strong>提供者：</strong>(业务组提供)
 * <p>
 * <strong>使用者：</strong>(使用业务组，若分方法描述可省略此项)
 * <p>
 * <strong>设计状态：</strong>(支出接口类设计阶段：总体，详细)
 * <p>
 * @CreatTime 2025-0422  20:28
 **/
public class   ServerRequestHandler  extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //1,读取
        Packmsg  packmsg = (Packmsg) msg;
        System.out.println("[server read]读取到请求头，id："+packmsg.getHeader().getRequestID());
        System.out.println("[server read]invocation的interfaceName："+packmsg.getInvocation().getInterfaceName());
        System.out.println("[server read]invocation的methodName："+packmsg.getInvocation().getMethodName());
        System.out.println("[server read]invocation的第一个参数："+packmsg.getInvocation().getParameter()[0]);
        //io线程名称
        String ioThreadName = Thread.currentThread().getName();
        //2,处理
        ctx.executor().execute(new Runnable() {
            @Override
            public void run() {
                //执行线程名称
                String exeThreadName = Thread.currentThread().getName();
                //打印线程信息
                System.out.println("[server read]执行线程："+exeThreadName+"io线程名称："+ioThreadName);
                //todo 改进可以使用map把interfaceName和实体类做一个映射
                String s="hello"+packmsg.getInvocation().getParameter()[0];
               //封装返回体
                Invocation invocation = packmsg.getInvocation();
                invocation.setRes(s);
                //序列化返回请求体
                byte[] invocationByteArray = SerDerUtil.ser(invocation);
                //封装返回请求头
                NettyHeader header = new NettyHeader(0x14141424,  packmsg.getHeader().getRequestID(),invocationByteArray.length);
                //序列化返回请求头
                byte[] headerByteArray = SerDerUtil.ser(header);
                ByteBuf byteBuf= PooledByteBufAllocator.DEFAULT.directBuffer(invocationByteArray.length+headerByteArray.length);
                byteBuf.writeBytes(headerByteArray);
                byteBuf.writeBytes(invocationByteArray);
                System.out.println("[server read]处理完成");
                //返回
                ctx.writeAndFlush(byteBuf);
            }
        });
        //3，返回

    }
}
